package oracle.to.mysql.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
* @description 身份证转换工具
*/
public class IdCardUtil {
	private static Map<Integer, String> map = new HashMap<Integer, String>();
	private static String cid = "";
	public static void main(String[] args) throws Exception{
//		String value = "211002199101304835";
//		IdCardUtil id =new IdCardUtil(value);// 
//		if (value.length() == 15 || value.length() == 18){
//			String lastValue = value.substring(value.length() - 1, value.length());
//			int sex;
//			if (lastValue.trim().toLowerCase().equals("x")||lastValue.trim().toLowerCase().equals("e")){
//				System.out.println( "先生");
//			} else {
//				sex = Integer.parseInt(lastValue) % 2;
//				System.out.println(sex == 0 ? "女士" : "先生");
//			}
//		}
	}
	public IdCardUtil(String id) throws Exception {
		if (id.length() != 18) {
			throw new Exception("身份证号不是18位！");
		}
		setCid(id);
		initMap();
	}
	
	private void setCid(String cid) {
		IdCardUtil.cid = cid.toUpperCase();
	}

	public long getBirthday() {
		String birthday = cid.substring(6, 10) + "-" + cid.substring(10, 12)
				+ "-" + cid.substring(12, 14);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		long time = 0;
		try {
			time = sdf.parse(birthday).getTime();
		} catch (ParseException e) {
		}
		return time;
	}

	public String getSex() {
		String sex = "";
		try {
			Integer i=Integer.parseInt(cid.substring(16, 17));
			if (i > 0 && i % 2 == 1) {
				sex = "1";
			} else {
				sex = "2";
			}
		} catch (NumberFormatException e) {
		}
		return sex;
	}

	public List<String> getCity() {
		String cityCode = cid.substring(0, 2);
		String cityName = map.get(Integer.valueOf(cityCode));
		List<String> list = new ArrayList<String>();
		list.add(cityCode);
		list.add(cityName);
		return list;
	}
	
	public String getCityExact() {
		return cid.substring(0, 6);
	}
	
	/**
	 * 身份证的有效验证
	 */
	public boolean validate() {
		String[] ValCodeArr = { "1", "0", "X", "9", "8", "7", "6", "5", "4",
				"3", "2" };
		String[] Wi = { "7", "9", "10", "5", "8", "4", "2", "1", "6", "3", "7",
				"9", "10", "5", "8", "4", "2" };
		String Ai = "";
		if (cid.length() != 15 && cid.length() != 18) {// 身份证号码长度应该为15位或18位
			return false;
		}
		// ================ 数字 除最后以为都为数字 ================
		if (cid.length() == 18) {
			Ai = cid.substring(0, 17);
		} else if (cid.length() == 15) {
			Ai = cid.substring(0, 6) + "19" + cid.substring(6, 15);
		}
		if (isNumeric(Ai) == false) {// 身份证15位号码都应为数字 ; 18位号码除最后一位外，都应为数字。
			return false;
		}
		// ================ 出生年月是否有效 ================
		String strYear = Ai.substring(6, 10);// 年份
		String strMonth = Ai.substring(10, 12);// 月份
		String strDay = Ai.substring(12, 14);// 月份
		if (isDataFormat(strYear + "-" + strMonth + "-" + strDay) == false) {// 身份证生日无效。
			return false;
		}
		GregorianCalendar gc = new GregorianCalendar();
		SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd");
		try {
			if ((gc.get(Calendar.YEAR) - Integer.parseInt(strYear)) > 150
					|| (gc.getTime().getTime() - s.parse(
							strYear + "-" + strMonth + "-" + strDay).getTime()) < 0) {// 身份证生日不在有效范围。
				
				return false;
			}
		} catch (ParseException e) {
			return false;
		}
		if (Integer.parseInt(strMonth) > 12 || Integer.parseInt(strMonth) == 0) {// 身份证月份无效
			return false;
		}
		if (Integer.parseInt(strDay) > 31 || Integer.parseInt(strDay) == 0) {// 身份证日期无效
			return false;
		}
		if (getCity().isEmpty()) {// 身份证地区编码错误。
			return false;
		}
		int TotalmulAiWi = 0;
		for (int i = 0; i < 17; i++) {
			TotalmulAiWi = TotalmulAiWi
					+ Integer.parseInt(String.valueOf(Ai.charAt(i)))
					* Integer.parseInt(Wi[i]);
		}
		int modValue = TotalmulAiWi % 11;
		String strVerifyCode = ValCodeArr[modValue];
		Ai = Ai + strVerifyCode;
		if (cid.length() == 18) {
			if (Ai.equals(cid) == false) {// 身份证无效，不是合法的身份证号码
				return false;
			}
		} else {
			return true;
		}
		return true;
	}
	private boolean isDataFormat(String str) {
		boolean flag = false;
		// String
		// regxStr="[1-9][0-9]{3}-[0-1][0-2]-((0[1-9])|([12][0-9])|(3[01]))";
		String regxStr = "^((\\d{2}(([02468][048])|([13579][26]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])))))|(\\d{2}(([02468][1235679])|([13579][01345789]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|(1[0-9])|(2[0-8]))))))(\\s(((0?[0-9])|([1-2][0-3]))\\:([0-5]?[0-9])((\\s)|(\\:([0-5]?[0-9])))))?$";
		Pattern pattern1 = Pattern.compile(regxStr);
		Matcher isNo = pattern1.matcher(str);
		if (isNo.matches()) {
			flag = true;
		}
		return flag;
	}

	private boolean isNumeric(String str) {
		Pattern pattern = Pattern.compile("[0-9]*");
		Matcher isNum = pattern.matcher(str);
		if (isNum.matches()) {
			return true;
		} else {
			return false;
		}
	}
	
	//转换大小写
	public String charToUpperCase(String id){
		return id.replaceAll("x", "X");
	}
	
	/*
	 * 获取年龄
	 */
   public int getAgeByIdCard() {
        int iAge = 0;
        Calendar cal = Calendar.getInstance();
        String year = cid.substring(6, 10);
        int iCurrYear = cal.get(Calendar.YEAR);
        iAge = iCurrYear - Integer.valueOf(year);
        return iAge;
    }
   
	private void initMap() {
		map.put(11, "北京市");
		map.put(12, "天津市");
		map.put(13, "河北省");
		map.put(14, "山西省");
		map.put(15, "内蒙古自治区");
		map.put(21, "辽宁省");
		map.put(22, "吉林省");
		map.put(23, "黑龙江省");
		map.put(31, "上海市");
		map.put(32, "江苏省");
		map.put(33, "浙江省");
		map.put(34, "安徽省");
		map.put(35, "福建省");
		map.put(36, "江西省");
		map.put(37, "山东省");
		map.put(41, "河南省");
		map.put(42, "湖北省");
		map.put(43, "湖南省");
		map.put(44, "广东省");
		map.put(45, "广西壮族自治区");
		map.put(46, "海南省");
		map.put(50, "重庆市");
		map.put(51, "四川省");
		map.put(52, "贵州省");
		map.put(53, "云南省");
		map.put(54, "西藏自治区 ");
		map.put(61, "陕西省");
		map.put(62, "甘肃省");
		map.put(63, "青海省");
		map.put(64, "宁夏回族自治区");
		map.put(65, "新疆维吾尔自治区");
		map.put(66, "新疆生产建设兵团");
		map.put(71, "台湾");
		map.put(81, "香港");
		map.put(82, "澳门");
		map.put(91, "国外 ");
	}
	
}
